package com.zbkj.common.utils;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.type.WhenNoDataTypeEnum;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimplePdfReportConfiguration;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

public class JasperReportUtil {

    /**
     * 根据 JRXML 模板生成 PDF 报表
     *
     * @param jrxmlPath      .jrxml 文件在 resources 下的相对路径，例如 "jasperReport/InspectionReport.jrxml"
     * @param parameters     报表参数
     * @param dataList       数据源列表（可为空）
     * @param outputFileName 输出不带.pdf的文件名（可为 null，则默认输出到 resources/jasperReport/output.pdf）
     * @return 生成的 PDF 文件路径
     */
    public static String generatePdfFromJrxml(
            String jrxmlPath,
            String savePath,
            Map<String, Object> parameters,
            List<Map<String, Object>> dataList,
            String outputFileName) {

        try {
            // 加载 JRXML 文件
            InputStream jrxmlInputStream = JasperReportUtil.class.getClassLoader().getResourceAsStream(jrxmlPath);
            if (jrxmlInputStream == null) {
                throw new RuntimeException("未找到jrxml文件 " + jrxmlPath);
            }

            JasperReport jasperReport = JasperCompileManager.compileReport(jrxmlInputStream);
            jasperReport.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL);

            // 填充报表
            JasperPrint jasperPrint = JasperFillManager.fillReport(
                    jasperReport,
                    parameters != null ? parameters : new HashMap<>(),
                    new JRBeanCollectionDataSource(dataList != null ? dataList : new ArrayList<>())
            );

            // 设置输出路径
            File resourceDir = new File(savePath);
            File targetDir = new File(resourceDir, "jasperReport");

            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            String outputFilePath = targetDir.getAbsolutePath();
            if (outputFileName == null || outputFileName.isEmpty()) {
                outputFilePath = new File(targetDir, "output.pdf").getAbsolutePath();
            }else{
                outputFilePath = new File(targetDir,outputFileName+".pdf").getAbsolutePath();
            }

            // 导出为 PDF
            JRExporter exporter = new JRPdfExporter();
            exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
            exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputFilePath));

            // 配置
            SimplePdfReportConfiguration reportConfig = new SimplePdfReportConfiguration();
            reportConfig.setSizePageToContent(true);
            exporter.setConfiguration(reportConfig);

            exporter.exportReport();

            return outputFilePath;

        } catch (JRException e) {
            throw new RuntimeException("生成 PDF 失败: " + e.getMessage(), e);
        }
    }
}
